﻿

function TwitterUsersHandler() {
    this.service = new TwitterService();
    var $table = $('#twitterUserTbody');
    iconify();
    var $dialog = $('#usersDialog');
    $dialog.dialog({
        autoOpen: false,
        height: 300,
        width: 500,
        modal: true,
        title: 'Twitter User Details',
        buttons: {
            'Save': function () {
                var obj = {};
                obj.ID = $('#UserID').val();
                obj.Name = $('#UserName').val();
                obj.IsBlog = ($("#IsBlog").attr("checked")) ? true : false;
                obj.IsNewspaper = ($("#IsNewspaper").attr("checked")) ? true : false;
                obj.IsTopJournalist = ($("#IsTopJournalist").attr("checked")) ? true : false;
                obj.IsTopPolitical = ($("#IsTopPolitical").attr("checked")) ? true : false;

                window.PageBus.publish(TwitterUsersHandler.save, obj);
            },
            'Close': function () {
                $dialog.dialog("close");
            }
        }
    });
    window.PageBus.subscribe(TwitterUsersHandler.add, this, this.addHandler, { table: $table });
    window.PageBus.subscribe(TwitterUsersHandler.edit, this, this.editHandler, { table: $table, dialog: $dialog });
    window.PageBus.subscribe(TwitterUsersHandler.remove, this, this.removeHandler, { table: $table });
    window.PageBus.subscribe(TwitterUsersHandler.save, this, this.saveHandler, { table: $table, dialog: $dialog });
}
TwitterUsersHandler.prototype.service = null;
TwitterUsersHandler.add = 'twitter.users.add';
TwitterUsersHandler.edit = 'twitter.users.edit';
TwitterUsersHandler.remove = 'twitter.users.remove';
TwitterUsersHandler.save = 'twitter.users.save';
TwitterUsersHandler.prototype.addHandler = function (subj, addInput, data) {
    var username = $("#" + addInput).val();
    function updateTable(result) {
        var row = document.createElement("tr");
        row.setAttribute("id", result.TwitterUser.ID);
        data.table.append(row);
        row.innerHTML = decode_utf8(result.Html);
        iconify();
        $("#" + addInput).val("");
    }
    this.service.addUser(false, username, updateTable);
};
TwitterUsersHandler.prototype.editHandler = function (subj, rowButton, data) {
    var $button = $(rowButton);
    this.$row = $button.parent().parent();
    $('#UserID').val($button.val());
    $('#UserName').val(this.$row.find(".UserName").text());
    var checked = false;
    checked = (this.$row.find(".IsBlog").text() == 'true') ? true : false;
    $('#IsBlog').attr('checked', checked);
    checked = (this.$row.find(".IsNewspaper").text() == 'true') ? true : false;
    $('#IsNewspaper').attr('checked', checked);
    checked = (this.$row.find(".IsTopJournalist").text() == 'true') ? true : false;
    $('#IsTopJournalist').attr('checked', checked);
    checked = (this.$row.find(".IsTopPolitical").text() == 'true') ? true : false;
    $('#IsTopPolitical').attr('checked', checked);
    data.dialog.dialog("open");
};
TwitterUsersHandler.prototype.removeHandler = function (subj, rowButton, $table) {
    var $button = $(rowButton);
    var row = $(rowButton).parent().parent();
    var studyID = $button.val();
    function removeRow() {
        row.remove();
    }
    this.service.removeStudy(studyID, removeRow);
};
TwitterUsersHandler.prototype.saveHandler = function (subj, obj, data) {
    function updateTable(result) {
        var row = data.table.find("tr[id='" + result.TwitterUser.ID + "']")
        row.html(decode_utf8(result.Html));
        iconify();
        data.dialog.dialog("close");
    }
    this.service.saveUser(obj, updateTable);
};






function TweetsHandler() {
    this.service = new TwitterService();
    this.$dialog = $("#tweetDetails");
    this.$dialog.dialog({
        autoOpen: false,
        height: 500,
        width: 800,
        modal: true,
        title: 'Tweet',
        buttons: {
            'Save': function () {
                window.PageBus.publish(TweetsHandler.save);
            },
            'Close': function () {
                window.PageBus.publish(TweetsHandler.close);
            },
            'Previous': function () {
                window.PageBus.publish(TweetsHandler.previous);
            },
            'Next': function () {
                window.PageBus.publish(TweetsHandler.next);
            }
        }
    });
    window.PageBus.subscribe(TweetsHandler.open, this, this.openHandler, this.$dialog);
    window.PageBus.subscribe(TweetsHandler.close, this, this.closeHandler, this.$dialog);
    window.PageBus.subscribe(TweetsHandler.save, this, this.saveHandler, this.$dialog);
    window.PageBus.subscribe(TweetsHandler.next, this, this.nextHandler, this.$dialog);
    window.PageBus.subscribe(TweetsHandler.previous, this, this.previousHandler, this.$dialog);
}
TweetsHandler.prototype.service = null;
TweetsHandler.open = "tweets.dialog.open";
TweetsHandler.close = "tweets.dialog.close";
TweetsHandler.save = "tweets.dialog.save";
TweetsHandler.next = "tweets.dialog.next";
TweetsHandler.previous = "tweets.dialog.previous";

TweetsHandler.prototype.nextHandler = function (subj, msg, popup) {
    $(".picklist span.selected").parent().next().find("span").click();
};
TweetsHandler.prototype.previousHandler = function (subj, msg, popup) {
    $(".picklist span.selected").parent().prev().find("span").click();
};
TweetsHandler.prototype.openHandler = function (subj, msg, popup) {
    $(".picklist span").removeClass('selected');
    $(msg.source).addClass('selected');
    function callback(results) {
        popup.html(results);
        $("#tabs").tabs();
        $("#tweetAttributes").buttonset();
        $(":checkbox").button();
        $(".toneList").buttonset();
        $('.Positive').button({ text: false, icons: { primary: 'ui-icon-plus'} })
        $('.Negative').button({ text: false, icons: { primary: 'ui-icon-minus'} })
        $('.Neutral').button({ text: false, icons: { primary: 'ui-icon-radio-on'} })
        popup.dialog("open");
    }
    this.service.getTweet(msg.id, callback);
};
TweetsHandler.prototype.closeHandler = function (subj, msg, popup) {
    popup.dialog("close");
};
TweetsHandler.prototype.saveHandler = function (subj, msg, popup) {
    var tweet = {};
    tweet.ID = $("#tweetID").val();
    tweet.IsClarification = ($("#IsClarification").attr("checked")) ? true : false;
    tweet.IsGeneral = ($("#IsGeneral").attr("checked")) ? true : false;
    tweet.IsQuestion = ($("#IsQuestion").attr("checked")) ? true : false;
    tweet.Genre = $("#tweetGenre").val();
    tweet.Links = [];
    tweet.Mentions = [];
    var links = $(".link");
    for (var i = 0; i < links.length; i++) {
        var id = parseInt(links[i].innerHTML);
        var isInternal = ($("#IsInternal-" + id).attr("checked")) ? true : false;
        var link = {
            Sequence: id,
            Tone: $("input[name='tweetLinkTone"+ id +"']:checked").val(),
            IsInternal: isInternal
        };
        tweet.Links.push(link);
    }
    var mentions = $(".mention");
    for (var i = 0; i < mentions.length; i++) {
        var id = parseInt(mentions[i].innerHTML);
        var isVia = ($("#IsVia-" + id).attr("checked")) ? true : false;
        var isRetweet = ($("#IsRetweet-" + id).attr("checked")) ? true : false;
        var mention = {
            Sequence: id,
            IsRetweet: isRetweet,
            IsVia: isVia
        };
        tweet.Mentions.push(mention);
    }
    //alert(JSON.stringify(tweet));
    function callback(result) {
        //popup.dialog("close");
        alert(result);
    }
    this.service.saveTweet(tweet, callback);
};


function TwitterService() { }
TwitterService.prototype.getTweet = function (tweetID, callback) {
    Service.get("/Twitter/Tweet/" + tweetID, null, callback, "html");
};
TwitterService.prototype.addUser = function (studyID, username, callback) {
    if (studyID)
        Service.post("/Twitter/AddUser/" + username + "/" + studyID, null, callback, "html");
    else
        Service.post("/Twitter/AddUser/" + username, null, callback, "json");
};
TwitterService.prototype.removeUser = function (studyID, username, callback) {
    Service.post("/Twitter/RemoveUser/" + studyID + "/" + username, null, callback, "html");
};
TwitterService.prototype.saveTweet = function (_tweet, callback) {
    var _data = JSON.stringify(_tweet);
    $.ajax({ type: 'POST', url: "/Twitter/SaveTweet", data: _data, success: callback, dataType: "json", contentType: "application/json; charset=utf-8", traditional: true });
};
